package com.xiguaji.tiktok.config.interceptor;


import com.xiguaji.boot.toolkit.HttpUtil;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.tiktok.utils.Ret;
import com.xiguaji.tiktok.utils.jwt.JwtUtil;
import com.xiguaji.tiktok.v1.tiktok.mytiktok.repository.TBloggerRepository;
import com.xiguaji.tiktok.v1.tiktok.permission.repository.UserRoleRepository;
import com.xiguaji.tiktok.v1.user.model.User;
import com.xiguaji.tiktok.v1.user.service.UserService;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
public class MyTikTokersInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtil jwtUtil;

    @Value("${jwt.head}")
    String authorized;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    TBloggerRepository tBloggerRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        User user = getUser();

        if(getRoleId(user) == 1){
            val tBloggers = tBloggerRepository.findByUserId(user.getId());

            if(tBloggers.size() > 0){
                // 免费版首次添加TikToker账号后，可以试用3天
                if((tBloggers.get(0).getCreateTime()+60*60*24*3) < System.currentTimeMillis()/1000){
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    val writer = response.getWriter();
                    writer.write(Ret.noPermission("1||Free trial expired!Please update your membership to continue using this feature."));//
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {

    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            {

    }

    private User getUser(){
        String token = HttpUtil.getCookie(authorized);

        if(StringUtils.isEmpty(token)){
            return null;
        }
        return JsonUtil.jsonParse(User.class,JsonUtil.parseJson(jwtUtil.getJwtUser(token).getUser()));
    }

    private long getRoleId(User user){
        long roleId = 1;

        val userRoleOptional = userRoleRepository.findTop1ByUserIdAndExpireTimeGreaterThanEqualOrderByRoleIdDesc(user.getParentId() == 0 ?user.getId():user.getParentId(), new Date());

        if(userRoleOptional.isPresent()){
            roleId = userRoleOptional.get().getRoleId();
        }
        return roleId;
    }
}
